home *** CD-ROM | disk | FTP | other *** search
/ Visual Cafe 3 / Visual Cafe 3.ISO / Vcafe / Sample.bin / ThreeD.java < prev    next >
Text File  |  1998-09-15  |  13KB  |  485 lines

  1. /*
  2.  * @(#)ThreeD.java    1.7 98/03/23
  3.  *
  4.  * Copyright (c) 1995-1997 Sun Microsystems, Inc. All Rights Reserved.
  5.  *
  6.  * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
  7.  * modify and redistribute this software in source and binary code form,
  8.  * provided that i) this copyright notice and license appear on all copies of
  9.  * the software; and ii) Licensee does not utilize the software in a manner
  10.  * which is disparaging to Sun.
  11.  *
  12.  * This software is provided "AS IS," without a warranty of any kind. ALL
  13.  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
  14.  * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
  15.  * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
  16.  * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
  17.  * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
  18.  * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
  19.  * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
  20.  * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
  21.  * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
  22.  * POSSIBILITY OF SUCH DAMAGES.
  23.  *
  24.  * This software is not designed or intended for use in on-line control of
  25.  * aircraft, air traffic, aircraft navigation or aircraft communications; or in
  26.  * the design, construction, operation or maintenance of any nuclear
  27.  * facility. Licensee represents and warrants that it will not use or
  28.  * redistribute the Software for such purposes.
  29.  */
  30.  
  31. /* A set of classes to parse, represent and display 3D wireframe models
  32.    represented in Wavefront .obj format. */
  33.  
  34. import java.applet.Applet;
  35. import java.awt.Graphics;
  36. import java.awt.Color;
  37. import java.awt.Event;
  38. import java.awt.event.*;
  39. import java.io.*;
  40. import java.net.URL;
  41.  
  42. class FileFormatException extends Exception {
  43.     public FileFormatException(String s) {
  44.     super(s);
  45.     }
  46. }
  47.  
  48. /** The representation of a 3D model */
  49. class Model3D {
  50.     float vert[];
  51.     int tvert[];
  52.     int nvert, maxvert;
  53.     int con[];
  54.     int ncon, maxcon;
  55.     boolean transformed;
  56.     Matrix3D mat;
  57.  
  58.     float xmin, xmax, ymin, ymax, zmin, zmax;
  59.  
  60.     Model3D () {
  61.     mat = new Matrix3D ();
  62.     mat.xrot(20);
  63.     mat.yrot(30);
  64.     }
  65.     /** Create a 3D model by parsing an input stream */
  66.     Model3D (InputStream is) throws IOException, FileFormatException {
  67.       this();
  68.       StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(is)));
  69.       st.eolIsSignificant(true);
  70.       st.commentChar('#');
  71.     scan:
  72.     while (true) {
  73.         switch (st.nextToken()) {
  74.           default:
  75.         break scan;
  76.           case StreamTokenizer.TT_EOL:
  77.         break;
  78.           case StreamTokenizer.TT_WORD:
  79.         if ("v".equals(st.sval)) {
  80.             double x = 0, y = 0, z = 0;
  81.             if (st.nextToken() == StreamTokenizer.TT_NUMBER) {
  82.             x = st.nval;
  83.             if (st.nextToken() == StreamTokenizer.TT_NUMBER) {
  84.                 y = st.nval;
  85.                 if (st.nextToken() == StreamTokenizer.TT_NUMBER)
  86.                 z = st.nval;
  87.             }
  88.             }
  89.             addVert((float) x, (float) y, (float) z);
  90.             while (st.ttype != StreamTokenizer.TT_EOL &&
  91.                 st.ttype != StreamTokenizer.TT_EOF)
  92.             st.nextToken();
  93.         } else if ("f".equals(st.sval) || "fo".equals(st.sval) || "l".equals(st.sval)) {
  94.             int start = -1;
  95.             int prev = -1;
  96.             int n = -1;
  97.             while (true)
  98.             if (st.nextToken() == StreamTokenizer.TT_NUMBER) {
  99.                 n = (int) st.nval;
  100.                 if (prev >= 0)
  101.                 add(prev - 1, n - 1);
  102.                 if (start < 0)
  103.                 start = n;
  104.                 prev = n;
  105.             } else if (st.ttype == '/')
  106.                 st.nextToken();
  107.             else
  108.                 break;
  109.             if (start >= 0)
  110.             add(start - 1, prev - 1);
  111.             if (st.ttype != StreamTokenizer.TT_EOL)
  112.             break scan;
  113.         } else {
  114.             while (st.nextToken() != StreamTokenizer.TT_EOL
  115.                 && st.ttype != StreamTokenizer.TT_EOF);
  116.         }
  117.         }
  118.     }
  119.     is.close();
  120.     if (st.ttype != StreamTokenizer.TT_EOF)
  121.         throw new FileFormatException(st.toString());
  122.     }
  123.  
  124.     /** Add a vertex to this model */
  125.     int addVert(float x, float y, float z) {
  126.     int i = nvert;
  127.     if (i >= maxvert)
  128.         if (vert == null) {
  129.         maxvert = 100;
  130.         vert = new float[maxvert * 3];
  131.         } else {
  132.         maxvert *= 2;
  133.         float nv[] = new float[maxvert * 3];
  134.         System.arraycopy(vert, 0, nv, 0, vert.length);
  135.         vert = nv;
  136.         }
  137.     i *= 3;
  138.     vert[i] = x;
  139.     vert[i + 1] = y;
  140.     vert[i + 2] = z;
  141.     return nvert++;
  142.     }
  143.     /** Add a line from vertex p1 to vertex p2 */
  144.     void add(int p1, int p2) {
  145.     int i = ncon;
  146.     if (p1 >= nvert || p2 >= nvert)
  147.         return;
  148.     if (i >= maxcon)
  149.         if (con == null) {
  150.         maxcon = 100;
  151.         con = new int[maxcon];
  152.         } else {
  153.         maxcon *= 2;
  154.         int nv[] = new int[maxcon];
  155.         System.arraycopy(con, 0, nv, 0, con.length);
  156.         con = nv;
  157.         }
  158.     if (p1 > p2) {
  159.         int t = p1;
  160.         p1 = p2;
  161.         p2 = t;
  162.     }
  163.     con[i] = (p1 << 16) | p2;
  164.     ncon = i + 1;
  165.     }
  166.     /** Transform all the points in this model */
  167.     void transform() {
  168.     if (transformed || nvert <= 0)
  169.         return;
  170.     if (tvert == null || tvert.length < nvert * 3)
  171.         tvert = new int[nvert*3];
  172.     mat.transform(vert, tvert, nvert);
  173.     transformed = true;
  174.     }
  175.  
  176.    /* Quick Sort implementation
  177.     */
  178.    private void quickSort(int a[], int left, int right)
  179.    {
  180.       int leftIndex = left;
  181.       int rightIndex = right;
  182.       int partionElement;
  183.       if ( right > left)
  184.       {
  185.  
  186.          /* Arbitrarily establishing partition element as the midpoint of
  187.           * the array.
  188.           */
  189.          partionElement = a[ ( left + right ) / 2 ];
  190.  
  191.          // loop through the array until indices cross
  192.          while( leftIndex <= rightIndex )
  193.          {
  194.             /* find the first element that is greater than or equal to 
  195.              * the partionElement starting from the leftIndex.
  196.              */
  197.             while( ( leftIndex < right ) && ( a[leftIndex] < partionElement ) )
  198.                ++leftIndex;
  199.  
  200.             /* find an element that is smaller than or equal to 
  201.              * the partionElement starting from the rightIndex.
  202.              */
  203.             while( ( rightIndex > left ) && 
  204.                    ( a[rightIndex] > partionElement ) )
  205.                --rightIndex;
  206.  
  207.             // if the indexes have not crossed, swap
  208.             if( leftIndex <= rightIndex ) 
  209.             {
  210.                swap(a, leftIndex, rightIndex);
  211.                ++leftIndex;
  212.                --rightIndex;
  213.             }
  214.          }
  215.  
  216.          /* If the right index has not reached the left side of array
  217.           * must now sort the left partition.
  218.           */
  219.          if( left < rightIndex )
  220.             quickSort( a, left, rightIndex );
  221.  
  222.          /* If the left index has not reached the right side of array
  223.           * must now sort the right partition.
  224.           */
  225.          if( leftIndex < right )
  226.             quickSort( a, leftIndex, right );
  227.  
  228.       }
  229.    }
  230.  
  231.    private void swap(int a[], int i, int j)
  232.    {
  233.       int T;
  234.       T = a[i]; 
  235.       a[i] = a[j];
  236.       a[j] = T;
  237.    }
  238.  
  239.  
  240.     /** eliminate duplicate lines */
  241.     void compress() {
  242.     int limit = ncon;
  243.     int c[] = con;
  244.     quickSort(con, 0, ncon - 1);
  245.     int d = 0;
  246.     int pp1 = -1;
  247.     for (int i = 0; i < limit; i++) {
  248.         int p1 = c[i];
  249.         if (pp1 != p1) {
  250.         c[d] = p1;
  251.         d++;
  252.         }
  253.         pp1 = p1;
  254.     }
  255.     ncon = d;
  256.     }
  257.  
  258.     static Color gr[];
  259.  
  260.     /** Paint this model to a graphics context.  It uses the matrix associated
  261.     with this model to map from model space to screen space.
  262.     The next version of the browser should have double buffering,
  263.     which will make this *much* nicer */
  264.     void paint(Graphics g) {
  265.     if (vert == null || nvert <= 0)
  266.         return;
  267.     transform();
  268.     if (gr == null) {
  269.         gr = new Color[16];
  270.         for (int i = 0; i < 16; i++) {
  271.         int grey = (int) (170*(1-Math.pow(i/15.0, 2.3)));
  272.         gr[i] = new Color(grey, grey, grey);
  273.         }
  274.     }
  275.     int lg = 0;
  276.     int lim = ncon;
  277.     int c[] = con;
  278.     int v[] = tvert;
  279.     if (lim <= 0 || nvert <= 0)
  280.         return;
  281.     for (int i = 0; i < lim; i++) {
  282.         int T = c[i];
  283.         int p1 = ((T >> 16) & 0xFFFF) * 3;
  284.         int p2 = (T & 0xFFFF) * 3;
  285.         int grey = v[p1 + 2] + v[p2 + 2];
  286.         if (grey < 0)
  287.         grey = 0;
  288.         if (grey > 15)
  289.         grey = 15;
  290.         if (grey != lg) {
  291.         lg = grey;
  292.         g.setColor(gr[grey]);
  293.         }
  294.         g.drawLine(v[p1], v[p1 + 1],
  295.                v[p2], v[p2 + 1]);
  296.     }
  297.     }
  298.  
  299.     /** Find the bounding box of this model */
  300.     void findBB() {
  301.     if (nvert <= 0)
  302.         return;
  303.     float v[] = vert;
  304.     float xmin = v[0], xmax = xmin;
  305.     float ymin = v[1], ymax = ymin;
  306.     float zmin = v[2], zmax = zmin;
  307.     for (int i = nvert * 3; (i -= 3) > 0;) {
  308.         float x = v[i];
  309.         if (x < xmin)
  310.         xmin = x;
  311.         if (x > xmax)
  312.         xmax = x;
  313.         float y = v[i + 1];
  314.         if (y < ymin)
  315.         ymin = y;
  316.         if (y > ymax)
  317.         ymax = y;
  318.         float z = v[i + 2];
  319.         if (z < zmin)
  320.         zmin = z;
  321.         if (z > zmax)
  322.         zmax = z;
  323.     }
  324.     this.xmax = xmax;
  325.     this.xmin = xmin;
  326.     this.ymax = ymax;
  327.     this.ymin = ymin;
  328.     this.zmax = zmax;
  329.     this.zmin = zmin;
  330.     }
  331. }
  332.  
  333. /** An applet to put a 3D model into a page */
  334. public class ThreeD extends Applet 
  335.   implements Runnable, MouseListener, MouseMotionListener {
  336.     Model3D md;
  337.     boolean painted = true;
  338.     float xfac;
  339.     int prevx, prevy;
  340.     float xtheta, ytheta;
  341.     float scalefudge = 1;
  342.     Matrix3D amat = new Matrix3D(), tmat = new Matrix3D();
  343.     String mdname = null;
  344.     String message = null;
  345.  
  346.     public void init() {
  347.     mdname = getParameter("model");
  348.     try {
  349.         scalefudge = Float.valueOf(getParameter("scale")).floatValue();
  350.     }catch(Exception e){};
  351.     amat.yrot(20);
  352.     amat.xrot(20);
  353.     if (mdname == null)
  354.         mdname = "model.obj";
  355.     resize(getSize().width <= 20 ? 400 : getSize().width,
  356.            getSize().height <= 20 ? 400 : getSize().height);
  357.     addMouseListener(this);
  358.     addMouseMotionListener(this);
  359.     }
  360.  
  361.     public void destroy() {
  362.         removeMouseListener(this);
  363.         removeMouseMotionListener(this);
  364.     }
  365.  
  366.     public void run() {
  367.     InputStream is = null;
  368.     try {
  369.         Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
  370.         is = new URL(getDocumentBase(), mdname).openStream();
  371.         Model3D m = new Model3D (is);
  372.         md = m;
  373.         m.findBB();
  374.         m.compress();
  375.         float xw = m.xmax - m.xmin;
  376.         float yw = m.ymax - m.ymin;
  377.         float zw = m.zmax - m.zmin;
  378.         if (yw > xw)
  379.         xw = yw;
  380.         if (zw > xw)
  381.         xw = zw;
  382.         float f1 = getSize().width / xw;
  383.         float f2 = getSize().height / xw;
  384.         xfac = 0.7f * (f1 < f2 ? f1 : f2) * scalefudge;
  385.     } catch(Exception e) {
  386.         md = null;
  387.         message = e.toString();
  388.     }
  389.     try {
  390.         if (is != null)
  391.         is.close();
  392.     } catch(Exception e) {
  393.     }
  394.     repaint();
  395.     }
  396.  
  397.     public void start() {
  398.     if (md == null && message == null)
  399.         new Thread(this).start();
  400.     }
  401.  
  402.     public void stop() {
  403.     }
  404.     
  405.     public  void mouseClicked(MouseEvent e) {
  406.     }
  407.     
  408.     public  void mousePressed(MouseEvent e) {
  409.         prevx = e.getX();
  410.         prevy = e.getY();
  411.         e.consume();
  412.     }
  413.  
  414.     public  void mouseReleased(MouseEvent e) {
  415.     }
  416.  
  417.     public  void mouseEntered(MouseEvent e) {
  418.     }
  419.  
  420.     public  void mouseExited(MouseEvent e) {
  421.     }
  422.     
  423.     public  void mouseDragged(MouseEvent e) {
  424.         int x = e.getX();
  425.         int y = e.getY();
  426.  
  427.         tmat.unit();
  428.         float xtheta = (prevy - y) * 360.0f / getSize().width;
  429.         float ytheta = (x - prevx) * 360.0f / getSize().height;
  430.         tmat.xrot(xtheta);
  431.         tmat.yrot(ytheta);
  432.         amat.mult(tmat);
  433.         if (painted) {
  434.             painted = false;
  435.             repaint();
  436.         }
  437.         prevx = x;
  438.         prevy = y;
  439.         e.consume();      
  440.     }
  441.   
  442.     public  void mouseMoved(MouseEvent e) {
  443.     }
  444.  
  445.     public void paint(Graphics g) {
  446.     if (md != null) {
  447.         md.mat.unit();
  448.         md.mat.translate(-(md.xmin + md.xmax) / 2,
  449.                  -(md.ymin + md.ymax) / 2,
  450.                  -(md.zmin + md.zmax) / 2);
  451.         md.mat.mult(amat);
  452.         md.mat.scale(xfac, -xfac, 16 * xfac / getSize().width);
  453.         md.mat.translate(getSize().width / 2, getSize().height / 2, 8);
  454.         md.transformed = false;
  455.         md.paint(g);
  456.         setPainted();
  457.     } else if (message != null) {
  458.         g.drawString("Error in model:", 3, 20);
  459.         g.drawString(message, 10, 40);
  460.     }
  461.     }
  462.  
  463.     private synchronized void setPainted() {
  464.     painted = true;
  465.     notifyAll();
  466.     }
  467. //    private synchronized void waitPainted() {
  468. //    while (!painted)
  469. //        wait();
  470. //    painted = false;
  471. //    }
  472.  
  473.     public String getAppletInfo() {
  474.         return "Title: ThreeD \nAuthor: James Gosling? \nAn applet to put a 3D model into a page.";
  475.     }
  476.     
  477.     public String[][] getParameterInfo() {
  478.         String[][] info = {
  479.             {"model", "path string", "The path to the model to be displayed."},
  480.             {"scale", "float", "The scale of the model.  Default is 1."}
  481.         };
  482.         return info;
  483.     }
  484. }
  485.